package main

import (
	"context"
	"fmt"
	"haodayizhi/global"
	"haodayizhi/router"
	util "haodayizhi/utils"
	"log"
	"os"
	"time"

	"github.com/go-redis/redis/v8"
	"gopkg.in/yaml.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var timeFormat = "2006-01-02 15:04:05"

func init() {
	// 捕获 init 中的 panic
	defer func() {
		if err := recover(); err != nil {
			// 记录错误到日志
			util.LogMessage("error", fmt.Sprintf("Panic recovered in init: %v", err))
			log.Printf("Panic recovered in init: %v", err)
			// 终止程序
			os.Exit(1)
		}
	}()
	// 读取配置文件
	data, err := os.ReadFile("./config/app.yaml")
	if err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}
	err = yaml.Unmarshal(data, &global.Config)
	if err != nil {
		log.Fatalf("Error parsing config file: %v", err)
	}

	// 初始化数据库连接
	// Initialize GORM MySQL connection
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		global.Config.Database.Connection.Username,
		global.Config.Database.Connection.Password,
		global.Config.Database.Connection.Host,
		global.Config.Database.Connection.Port,
		global.Config.Database.Connection.Database)
	global.Db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		util.LogMessage("error", fmt.Sprintf("Error connecting to database: %v", err))
		log.Fatalf("Error connecting to database: %v", err)
	}

	// Configure connection pool
	sqlDB, err := global.Db.DB()
	if err != nil {
		util.LogMessage("error", fmt.Sprintf("Error getting SQL DB instance: %v", err))
		log.Fatalf("Error getting SQL DB instance: %v", err)
	}

	sqlDB.SetMaxOpenConns(global.Config.Performance.ConnectionPoolSize)
	sqlDB.SetMaxIdleConns(global.Config.Performance.ConnectionPoolSize / 2) // Example of setting half as idle connections
	sqlDB.SetConnMaxLifetime(time.Hour)                                     // Example of setting max connection lifetime to 1 hour

	// 初始化 Redis 客户端
	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", global.Config.Cache.Host, global.Config.Cache.Port),
		Password: global.Config.Cache.Password, // no password set
		DB:       global.Config.Cache.Db,       // use default DB
	})
	ctx := context.Background()
	_, err = global.Rdb.Ping(ctx).Result()
	if err != nil {
		util.LogMessage("error", fmt.Sprintf("Error connecting to Redis: %v", err))
		log.Fatalf("Error connecting to Redis: %v", err)
	}
}

func main() {
	// 初始化路由
	router := router.Router()
	err := router.Run(fmt.Sprintf("%s:%d", global.Config.Server.Host, global.Config.Server.Port))
	if err != nil {
		util.LogMessage("error", fmt.Sprintf("Server failed to start: %v", err))
		log.Fatalf("Server failed to start: %v", err)
	}
}
